package no.ntnu.fp.net.co;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.Socket;


public class MessageReceiver implements Runnable {
	
	private Socket socket;
	private BufferedReader in;
	private MessageListener listener;
	
	public MessageReceiver(Socket socket, 
			MessageListener listener) {
		
		this.socket = socket;
		this.listener = listener;
		
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			System.err.println("IOException on socket inputstream");
		}
	}
	
	public void setListener(MessageListener listener) {
		
		this.listener = listener;
	}
	
	public void run() {
		
		while(true) {
			try {
				while (!in.ready()) {
					
					try {
						Thread.sleep(2);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
				String message = in.readLine();
				if (message != null && !message.equals(""))
					listener.messageReceived(message);
			} 
			catch (ConnectException e) {} 
			catch (IOException e) {}
			
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

}
